# coding=utf-8
import inspect
import json
import traceback

import global_var


from base import sg
from common import defines

from server_module.handler_module import handler_common

from utils import proto_util



g_msg_dict = {}

def add_msg(user_id, data_dict):
	global g_msg_dict
	if user_id not in g_msg_dict:
		g_msg_dict[user_id] = []
	g_msg_dict[user_id].append(data_dict)
	

def delay_send(func):
	async def wrapper(*args, **kwargs):
		from server_module.server import ConnMgr
		user_id = args[1]
		global g_msg_dict
		resp = None
		try:
			if inspect.iscoroutinefunction(func):
				resp = await func(*args, **kwargs)
			else:
				resp = func(*args, **kwargs)
		except:
			traceback.print_exc()
			g_msg_dict.pop(user_id, None)
		
		msg_list = g_msg_dict.get(user_id, [])
		for data_dict in msg_list:
			try:
				await ConnMgr.ins.send_data(user_id, json.dumps(data_dict))
			except:
				traceback.print_exc()
				print("协议发送异常 ",user_id, data_dict)
		g_msg_dict.pop(user_id, None)
		return resp
	return wrapper

async def handle_msg(user_id, msg: str):
	await HandlerMgr.ins.handle_msg(user_id, msg)


@sg.singleton
class HandlerMgr(sg.SingletonBase["HandlerMgr"]):
	def __init__(self):
		self.handler_module = {}
		self.init()
	
	def init(self):
		self.handler_module[defines.C2S_COMMON] = handler_common
		
	
	@delay_send
	async def handle_msg(self, user_id: int, msg: str):
		data = json.loads(msg)
		data["user_id"] = user_id
		print("recv ", data["type"], data["func"])
		await self.handler_module[data["type"]].handle(proto_util.from_json_dict(data))
		
